package com.qf.android.sport.fragment.news;


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.qf.android.sport.BR;
import com.qf.android.sport.R;
import com.qf.android.sport.adapter.CommentRecyclerAdapter;
import com.qf.android.sport.callback.HttpService;
import com.qf.android.sport.databinding.FragmentPagerBinding;
import com.qf.android.sport.entity.news.Contents;
import com.qf.android.sport.entity.news.Datas;
import com.qf.android.sport.entity.news.Tops;
import com.qf.android.sport.entity.news.TotalEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * A simple {@link Fragment} subclass.
 * 新闻ViewPager的碎片
 */
public class PagerFragment extends Fragment implements Callback<TotalEntity>, PtrHandler {


    private FragmentPagerBinding binding;
    private CommentRecyclerAdapter<Object> adapter;
    private HttpService service;
    private String title;
    private long startId = -1;
    private boolean loading = false;
    public static PagerFragment getInstance(String title) {
        PagerFragment fragment = new PagerFragment();
        Bundle bundle = new Bundle();
        bundle.putString("title", title);
        fragment.setArguments(bundle);
        return fragment;
    }

    public PagerFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pager, container, false);
        title = getArguments().getString("title");
        HashMap<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        map.put(Datas.class, Pair.create(R.layout.pager_images, BR.datas));
        map.put(Tops.class, Pair.create(R.layout.hot_item, BR.top));
        map.put(Contents.class, Pair.create(R.layout.content_item, BR.contents));
        adapter = new CommentRecyclerAdapter<Object>(getContext(), map, new ArrayList<>());
        binding.recycler.setAdapter(adapter);
        initData(title,new HashMap<String, String>());
        StoreHouseHeader header = new StoreHouseHeader(getContext());
        header.initWithString("loading......");
        header.setBackgroundColor(0xff000000);
        binding.ptr.addPtrUIHandler(header);
        binding.ptr.setHeaderView(header);
//        final ImageView image = new ImageView(getContext());
//        image.setImageResource(R.mipmap.ic_launcher);
//        binding.ptr.setHeaderView(image);
        binding.ptr.setPtrHandler(this);
//        binding.ptr.addPtrUIHandler(new PtrUIHandler() {
//            @Override
//            public void onUIReset(PtrFrameLayout frame) {
//                ViewCompat.setScaleY(image,1);
//                ViewCompat.setScaleX(image,1);
//                ViewCompat.setRotation(image, 0);
//                ViewCompat.animate(image).cancel();
//            }
//
//            @Override
//            public void onUIRefreshPrepare(PtrFrameLayout frame) {
//
//            }
////刷新开始
//            @Override
//            public void onUIRefreshBegin(PtrFrameLayout frame) {
//                ViewCompat.animate(image)
//                        .rotationBy(3600)
//                        .setDuration(30000)
//                        .start();
//            }
//
//            @Override
//            public void onUIRefreshComplete(PtrFrameLayout frame) {
//
//            }
//
//            @Override
//            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
//                float percent = ptrIndicator.getCurrentPercent();
//                percent = Math.min(percent, 1);
//                ViewCompat.setScaleY(image, percent);
//                ViewCompat.setScaleX(image, percent);
//            }
//        });
        binding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                View item = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
                int position = recyclerView.getChildAdapterPosition(item);
                Log.d("zzzz", "onScrolled: "+position);
                if (!loading && position > adapter.getItemCount()-5) {
                    HashMap<String, String> hashMap = new HashMap<String, String>();
                    hashMap.put("start_id", String.valueOf(startId));
                    loading = true;
                    initData(title,hashMap);
                }
            }
        });
        return binding.getRoot();
    }



    private void initData(String title, HashMap<String, String> hashMap) {
        service = new Retrofit.Builder()
                .baseUrl("http://api.lifxapi.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(HttpService.class);
        switch (title) {
            case "推荐":
                service.getData("0", null, "true", null, "397.3", true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "中国篮球":
                //channel_id=9&data_version=59.6&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("9", null, null, null, "59.6", true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "国际足球":
                //channel_id=1&data_version=216.9&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("1", null, null, null, "216.9", true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "NBA":
//channel_id=2&data_version=155.8&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("2", "155.8", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "综合":
//channel_id=7&data_version=137.4&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("7", "137.4", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "中国足球":
//channel_id=8&data_version=187.9&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("8", "187.9", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "竞猜":
//channel_id=13&data_version=4.0&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("13", "4.0", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "深度":
//channel_id=10&data_version=13.2&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("10", "13.2", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "高尔夫":
//channel_id=6&data_version=5.7&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("6", "5.7", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "羽毛球":
//channel_id=5&head_version=0.0&data_version=10.6&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("5", null, null, "0.0", "10.6", true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "网球":
//channel_id=3&data_version=23.2&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("3", "23.2", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "图说":
//channel_id=11&data_version=10.6&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("11", "10.6", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "铿锵玫瑰":
     //channel_id=20&data_version=10.1&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("20", "10.1", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "最“董”球":
     // channel_id=19&data_version=2.4&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("19", "2.4", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "视频":
     //channel_id=12&data_version=112.4&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false
                service.getData("12", "112.4", null, null, null, true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
            case "电竞":
      //channel_id=17&head_version=0.0&data_version=2.2&banner_flag=true&machine_code=865682026799303&client=key%3ATiyuForAndroid&version=2.11&format=json&app_id=4&is_emulator=false"
                service.getData("17", null, null, "0.0", "2.2", true, "865682026799303", "key%3ATiyuForAndroid", "2.11", "json", "4", false,hashMap).enqueue(this);
                break;
        }

    }


    @Override
    public void onResponse(Call<TotalEntity> call, Response<TotalEntity> response) {
        if (startId == -1) {
        adapter.clear();
        }
        TotalEntity body = response.body();
        if (body.getData().getBanners() != null && body.getData().getBanners().size() != 0) {
            adapter.add(body.getData());
        }

        if (body.getData().getTops() != null && body.getData().getTops().size() != 0) {
            adapter.addAll(body.getData().getTops());
        }
        adapter.addAll(body.getData().getContents());
        List<Contents> contentses=body.getData().getContents();
        startId = contentses.get(contentses.size() - 1).getId();
        Log.d("zzzzz", "onResponse: "+startId);
        binding.ptr.refreshComplete();
        loading = false;

    }

    @Override
    public void onFailure(Call<TotalEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        binding.ptr.refreshComplete();
        loading = false;
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {

        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        startId = -1;
        initData(title, new HashMap<String, String>());
    }
}
